package com.gowants.pems.service;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.gowants.pems.mapper.SysPermissionMapper;
import com.gowants.pems.mapper.SysPowerMapper;
import com.gowants.pems.model.SysPermission;
import com.gowants.pems.util.Const;
import com.gowants.pems.util.DateUtil;
import com.gowants.pems.util.FileTypeJudge;
import com.gowants.pems.util.UploadUtil;

@Service(value = "scmsPermissionService")
public class SysPermissionService extends NewBaseService<SysPermission> {

	@Autowired
	private SysPermissionMapper scmsPermissionMapper;
	@Autowired
	private SysPowerMapper scmsPowerMapper;
	@Autowired
	private ParamsService paramsService;
//	private paramsService paramsService;
	@Override
	public int save(SysPermission record) {
		return scmsPermissionMapper.save(record);
	}

	@Override
	public int delete(String primaryKey) {
		return scmsPermissionMapper.delete(primaryKey);
	}

	@Override
	public int update(SysPermission record) {
		return scmsPermissionMapper.update(record);
	}

	@Override
	public SysPermission selectOne(String primaryKey) {
		return scmsPermissionMapper.selectOne(primaryKey);
	}

	@Override
	public List<SysPermission> select(SysPermission record) {
		return scmsPermissionMapper.select(record);
	}
	public List<SysPermission> selectPower(SysPermission record) {
		return scmsPermissionMapper.selectPower(record);
	}
	
	@Override
	public int getCount(SysPermission record) {
		return 0;
	}

	/**
	 * 启用禁用
	 * 
	 * @param id
	 * @return
	 */
	@Transactional(rollbackFor = Exception.class)
	public String isenable(String id) {
		String code = "TSMS_0000108";// 禁用成功
		int i = 0;
		SysPermission fp = scmsPermissionMapper.selectOne(id);
		if (null != fp) {
			List<SysPermission> list = scmsPermissionMapper.selectChildren(id);
			for (SysPermission fps : list) {
			    SysPermission record = new SysPermission();
				record.setId(fps.getId());
				if (fp.getIsenable() == 0) {
					record.setIsenable(1);
				} else {
					record.setIsenable(0);
				}
				i = scmsPermissionMapper.update(record);
			}
		}
		if (i > 0) {
			if (fp.getIsenable() == 0) {
				code = "TSMS_0000107";// 禁用成功
			} else {
				code = "TSMS_0000108";// 启用成功
			}
		} else {
			code = "TSMS_0000153";
		}
		return code;
	}

	@Transactional(rollbackFor = Exception.class)
	public int deleteAll(String primaryKey) {
		int i = 0;
		String path = paramsService.getParamValueByNumber(Const.icon_path);
		List<SysPermission> list = scmsPermissionMapper.selectChildren(primaryKey);
		for (SysPermission fps : list) {
			i = i + scmsPermissionMapper.delete(fps.getId());
            File file = new File(path+fps.getIcon());
            if(file.exists()) 
            {
                file.delete();
            }
			scmsPowerMapper.deleteBypermissionId(fps.getId());
		}
		return i;

	}

	/**
	 * 递归查询所有子集
	 * 
	 * @param id
	 * @return
	 */
	public List<SysPermission> selectALLChildren(SysPermission record) {
		return scmsPermissionMapper.selectALLChildren(record);
	}
	
	
	/**
	 * <上传文件校验大小及格式>
	 *
	 * @param
	 * @return -1 大小不符合规定 0 上传类型不符合规定 1 校验通过
	 * @remake create by GJR 2019/7/1 11:31
	 */
	public int uploadCheck(MultipartFile myFile, String fileType, String fileSize) {
		if (!uploadFileSizeCheck(myFile, fileSize)) {
			return -1;
		}

		if (!uploadFileTypeCheck(myFile, fileType)) {
			return 0;
		}

		return 1;
	}

	/**
	 * <上传文件校验>
	 *
	 * @param
	 * @return
	 * @remake
	 */
	public boolean uploadFileSizeCheck(MultipartFile myFile, String fileSize) {
		// 文件大小不符合规定
		String size = paramsService.getParamValueByNumber(fileSize);

		// 未定义视为没限制
		if (null == size || "".equals(size)) {
			return true;
		}

		// 字节单位比较，数据库配置单位是MB
		if (myFile.getSize() > Long.valueOf(size) * 1024 * 1024) {
			return false;
		}

		return true;
	}

	/**
	 * <文件格式校验>
	 *
	 * @param
	 * @return
	 * @remake
	 */
	public boolean uploadFileTypeCheck(MultipartFile myFile, String fileType) {

		// 图片格式不符合规定
		String fileName = UploadUtil.getFileName(myFile);

		// 格式正则配置
		String type = paramsService.getParamValueByNumber(fileType);

		// 未定义视为没限制
		if (null == type || "".equals(type)) {
			return true;
		}

		if (!fileName.matches(type)) {
			return false;
		}
		return true;

	}

	public String downloadPath(String pathConfig) {

		String path = paramsService.getParamValueByNumber(pathConfig);
		return path;
	}

	/**
	 * <文件上传>
	 *
	 * @param myFile 文件 pathConfig 文件保存根路径 isRelpaceFileName 是否更换文件名 isCreateDir
	 *               是否创建新文件夹 isRelpaceFileName true: 文件名_时间戳 isCreateDir true:
	 *               按当前时间创建文件夹
	 * @return
	 * @remake
	 */
	public String upload(MultipartFile myFile, String pathConfig, String relativePath, String mappingPath,
			boolean isRelpaceFileName, boolean isCreateDir) {
		String result = "";
		String fileName = UploadUtil.getFileName(myFile);
		try {
			// 设置文件全限定名
			String path = paramsService.getParamValueByNumber(pathConfig);
			// 是否更换文件名
			if (isRelpaceFileName) {
				// fileName.
				// String[] fNames = fileName.split("\\.");
				SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
				Random rand = new Random();
				int x = rand.nextInt(999);
				String fNames = fileName.substring(fileName.lastIndexOf(".") + 1);// 后缀
				fileName = df.format(new Date()) + x + "." + fNames;

			}

			// 是否创建文件夹
			if (isCreateDir) {
				String dir = DateUtil.getDays();
				fileName = dir + "/" + fileName;
			}
			// 拼接保存文件的全限定名
			String filePath = "";

			if (StringUtils.isNotBlank(relativePath)) {
				filePath += ("/" + relativePath);
			}
			filePath += ("/" + fileName);

			UploadUtil.saveFileFromInputStream(myFile.getInputStream(), path + filePath);
			// result = filePath.replace(path, "");
			result = filePath;
		} catch (Exception e) {
			e.printStackTrace();
		}

		return result;
	}
	public String uploadNew(MultipartFile myFile, String pathConfig, String relativePath, String mappingPath,
			boolean isRelpaceFileName, boolean isCreateDir) {
		String result = "";
		try {
			String fileName = UploadUtil.getFileName(myFile);
			// 设置文件全限定名
			String path = paramsService.getParamValueByNumber(pathConfig);
			// 是否更换文件名
			if (isRelpaceFileName) {
				// fileName.
				// String[] fNames = fileName.split("\\.");
				SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");// 设置日期格式
				Random rand = new Random();
				int x = rand.nextInt(999);
				String fNames = fileName.substring(fileName.lastIndexOf(".") + 1);// 后缀
				fileName = df.format(new Date()) + x + "." + fNames;

			}

			// 是否创建文件夹
			if (isCreateDir) {
				String dir = DateUtil.getDays();
				fileName = dir + "/" + fileName;
			}
			// 拼接保存文件的全限定名
			String filePath = "";

			if (StringUtils.isNotBlank(relativePath)) {
				filePath += ("/" + relativePath);
			}
			filePath += ("/" + fileName);
			FileTypeJudge.resize1(myFile.getInputStream(), path + filePath);
			UploadUtil.saveFileFromInputStream(myFile.getInputStream(), path + filePath);
			result = filePath;

		} catch (Exception e) {
			return "xxxxxxxxxx";

		}

		return result;

	}
}
